<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="序号">
          <template #default="obj">
            {{ obj.$index + 1 + pageParams.pagesize * (pageParams.page - 1) }}
          </template>
        </el-table-column>
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{ row }">
            <div v-if="!row.isEdit">{{ row.name }}</div>
            <!-- 3. 使用复制的数据 双向绑定 -->
            <el-input v-else v-model="row.editRowData.name" />
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template #default="{ row }">
            <div v-if="!row.isEdit">{{ row.state ? '已启用' : '未启用' }}</div>
            <!-- 3. 使用复制的数据 双向绑定 -->
            <el-switch v-else v-model="row.editRowData.state" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{ row }">
            <div v-if="!row.isEdit">{{ row.description }}</div>
            <!-- 3. 使用复制的数据 双向绑定 -->
            <el-input v-else v-model="row.editRowData.description" type="textarea" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <!-- 1. 做条件渲染 -->
            <div v-if="!row.isEdit">
              <el-button size="mini" type="text" @click="onShowPerm(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="row.isEdit = true">编辑</el-button>
              <el-button size="mini" type="text">删除</el-button>
            </div>
            <div v-else>
              <el-button size="mini" type="primary" @click="onUpdate(row)">确定</el-button>
              <el-button size="mini" @click="onCancel(row)">取消</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          :current-page="pageParams.page"
          @current-change="changePage"
        />
      </el-row>
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
        <!-- 表单内容 -->
        <el-form ref="roleForm" :model="formData" :rules="rules" label-width="120px">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="formData.name" style="width:300px" size="mini" />
          </el-form-item>

          <el-form-item label="启用">
            <el-switch v-model="formData.state" size="mini" />
          </el-form-item>

          <el-form-item prop="description" label="角色描述">
            <el-input v-model="formData.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>

          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="onSubmit">确定</el-button>

                <el-button size="mini">取消</el-button>

              </el-col>

            </el-row>

          </el-form-item>

        </el-form>

      </el-dialog>
    </div>
    <!--  2. 准备dialog -->
    <el-dialog title="分配权限" :visible.sync="permShow">
      <!-- expand-on-click-node 关闭点击折叠节点 -->
      <!--  show-checkbox 开启复选框 -->
      <!-- default-checked-keys 设置默认选中的节点 -->
      <!-- node-key 告诉树, id字段是唯一的 -->
      <!-- check-strictly:  关闭父子联动 -->
      <!-- $refs.xxx.getCheckedKeys() 可以获取用户选中的节点 -->
      <!--  6. :data绑定给树组件 -->
      <el-tree
        ref="treeRef"
        node-key="id"
        :default-checked-keys="checkedPermIds"
        :check-strictly="true"
        show-checkbox
        :data="permList"
        default-expand-all
        :props="{ label: 'name' }"
        :expand-on-click-node="false"
      />

      <el-row :style="{ paddingTop: '20px' }" type="flex" justify="center">
        <!-- 2. -->
        <el-button size="mini" type="primary" @click="onAssignPerm">分配权限</el-button>
        <el-button size="mini" @click="permShow = false">取消</el-button>
      </el-row>

    </el-dialog>
  </div>
</template>
<script>
// 给角色分配权限
// 1. 准备boolean控制弹出层显示和隐藏

// 3. 点击事件, 显示dialog
// 4. 准备树组件
// 5. 发请求, 查所有的权限, 保存到data中
import { getPermissionListAPI } from '@/api/permission'
import { addRoleAPI, assignPermAPI, getRoleDetailAPI, getRoleList, updateRoleAPI } from '@/api/role'
import { arrayToTree } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      // 准备checkedPermIds, 保存当前角色拥有的权限id
      checkedPermIds: [],
      // 控制分配权限的弹出层
      permShow: false,
      permList: [],
      list: [],
      showDialog: false,
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      formData: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    showDialog(newV) {
      if (!newV) {
        this.$refs.roleForm.resetFields()
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async onAssignPerm() {
      const checkedKeys = this.$refs.treeRef.getCheckedKeys()
      await assignPermAPI({ id: this.roleId, permIds: checkedKeys })
      this.$message.success('分配权限成功')
      this.permShow = false
    },
    async onShowPerm(id) {
      const res = await getPermissionListAPI()
      // 查询已有权限id
      const { permIds } = await getRoleDetailAPI(id)
      this.roleId = id
      this.checkedPermIds = permIds
      this.permList = arrayToTree(res)
      this.permShow = true
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      // 给list中每一个元素，分配一个isEdit属性 表示是否正在编辑的 开关表示
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRowData', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = total
    },
    changePage(val) {
      this.pageParams.page = val
      this.getRoleList()
    },
    async onSubmit() {
      await this.$refs.roleForm.validate()
      // 发送请求
      await addRoleAPI(this.formData)
      this.$message.success('添加成功')
      this.getRoleList()
      this.showDialog = false
    },
    onCancel(row) {
      // 4. 还原数据并关闭编辑状态
      row.editRowData = {
        name: row.name,
        state: row.state,
        description: row.description
      }
      row.isEdit = false
    },
    async onUpdate(row) {
      // 2. 校验数据不为空
      if (!row.editRowData.name) return this.$message.error('角色名称不能为空')
      if (!row.editRowData.description) return this.$message.error('角色描述不能为空')

      // 3. 调用API
      await updateRoleAPI({ id: row.id, ...row.editRowData })
      // 4. 提示用户和刷新数据
      this.$message.success('修改成功')
      this.getRoleList()
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
